package com.anhry.app.safety.manage.oa.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.oa.bean.TbOaMsg;
import com.anhry.app.safety.manage.oa.bean.TbOaMsgFj;
import com.anhry.app.safety.manage.oa.struts.base.OABaseAction;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.system.bean.TbUserDept;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Page;
import com.anhry.app.safety.util.UploadFile;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.UtilMethod;

@Controller
@Scope("prototype")
@SuppressWarnings("unchecked")
public class MsgAction extends OABaseAction{

	private String searchType; //搜索关键字类型
	private String key; //搜索关键字
	private String beginDate;
	private String endDate;
	private String search; //是否解码
	private String acceptTypeForwardId; //1，采纳类型列表
	
	private List msgList; //信息列表
	private List msgFjList; //附件列表
	private List acceptType; //采纳类型列表
	private List gradeList; //用户级别列表
	private String doneAcceptType; //存储到数据库中已设置采纳类型字符串
	
	private String id; 
	private String ids; //删除的多条信息id
	private String fjId; //附件id
	private String gradeId; 
	private String unitId;
	private String cGrade;
	private String cUnit;
	private String cDept;
	private boolean addOk;
	private String forwardPage;
	
	private TbOaMsg msg; //信息
	private TbOaMsgFj msgFj; //
	private String file; // 需要下载的文件名,通过链接传过来
	private String fName; 
	private String filePath;
	private File[] doc;
	private String[] docFileName;
	private String suffix; //后缀
	
	private String[] acceptStatus; //从数据库中查出并分割的已选择采纳类型
	private String newsContent; //信息内容
	private String readStatus; //读取状态
	
	private String menuId; //页面的显示元素
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 解码
	 *
	 */
	public void checkSearch() {
		if (this.search == null || !"1".equals(this.search)) {
			key = this.contextPvd.decode(this.key);
			searchType = this.contextPvd.decode(this.searchType);
		}
	}
	
	/**
	 * 查找采纳类型列表和已设置列表
	 * @return
	 */
	public String loadAcceptType(){
		try {
			acceptType = (List)this.utilService.getHqlQuery("from TbOaMsgType t where t.isDele=0");
			if (acceptTypeForwardId != null && acceptTypeForwardId.equals("1")) {
				formatAcceptType((List) this.utilService.getHqlQuery("select m.acceptStatus from TbOaMsg m where m.id=" + id));
				result = "accept_type_set";
				return SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("MsgAction:loadAcceptType 出错:" + e.getMessage());
		}
		return "";
	}
	
	/**
	 * 如果不是0，表示已设置，页面显示已经选择的类型
	 * @param list
	 */
	public void formatAcceptType(List list){
		if (list != null){
			StringBuffer tempString = new StringBuffer(list.get(0).toString());
			if (!tempString.equals("0")){
				doneAcceptType = tempString.toString();
			}
		}
	}
	
	/**
	 * 信息列表方法
	 * @return
	 */
	public String msgList(){
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			int num = 1; // 初始页码
			int rowCount = 0; // 记录总数
			int size = 10; // 定义分页的每页显示的初始个数
			if (super.num != null && !"".equals(super.num)) {
				num = Integer.parseInt(super.num);
			}
			if (super.size != null && !"".equals(super.size)) {
				size = Integer.parseInt(super.size);
			}
			checkSearch();
			loadAcceptType();
			StringBuffer hqlString = new StringBuffer("select count(*) from Tb_Oa_Msg m LEFT JOIN tb_user_grade g ON m.msg_grade = g.id LEFT JOIN tb_user_dept d ON m.msg_dept = d.id LEFT JOIN tb_user u ON m.msg_user = u.id LEFT JOIN tb_user_dept d2 ON m.msg_unit = d2.id where m.is_Dele=0");
			if (!"".equals(beginDate) && beginDate != null) {
				hqlString.append(" and m.msg_Time >= to_date('").append(beginDate).append("','yyyy-MM-dd')");
			}
			if (!"".equals(endDate) && endDate != null) {
				hqlString.append(" and m.msg_Time <= to_date('").append(endDate).append("','yyyy-MM-dd')");
			}
			if (!"".equals(searchType) && searchType != null){
				hqlString.append(" and m.accept_Name like '%").append(searchType).append("%'");
			}
			if (!"".equals(key) && key != null){
				hqlString.append(" and m.msg_Title like'%").append(key).append("%'");
			}
			if (!"".equals(readStatus) && readStatus != null) {
				//2为页面上阅读状态为所有，0为未读 1为已读
				if (!readStatus.equals("2")) {
					hqlString.append(" and m.read_Status = ").append(readStatus);
				}
			}
			if (!"".equals(cGrade) && cGrade != null){
				hqlString.append(" and m.msg_Grade = ").append(cGrade);
			}
			if (!"".equals(cDept) && cDept != null){
				hqlString.append(" and m.msg_Dept = ").append(cDept);
			}
			if (!"".equals(cUnit) && cUnit != null){
				hqlString.append(" and m.msg_Unit = ").append(cUnit);
			}
			if (menuId.equals("0")){
				hqlString.append(" and m.msg_user = ").append(user.getId());
			}
			List list = (List)this.utilService.getObjectBySql(hqlString.toString(),0,0);
			
			if (list != null && Integer.parseInt(list.get(0)+"")>0) {
				int resultCou = Integer.parseInt(list.get(0)+"");
				Page page = new Page(size, num, resultCou);
				this.setPage(page);
				String tempString = hqlString.toString().replace("select count(*) ", "select m.*,g.grade_name,d.dept_name dept,u.user_name,d2.dept_name unit ");
				msgList = this.utilService.getObjectBySql(tempString, page.getStartRow(), page.getSize());
			}
			this.setGradeList((List)this.utilService.getHqlQuery("from TbUserGrade g where g.id in (3,4,5,6,7)"));
			result = "msg_list";
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("msgAction:msgList()出错" + e);
		}
		tip = "加载出错！";
		return ERROR;
	}
	
	/**
	 * 加载部门、单位
	 */
	public void loadDept(){
		this.contextPvd.getResponse().setCharacterEncoding("utf-8");
		List<TbUserDept> list = null;
		StringBuffer opts = new StringBuffer();
		try {
			list = this.getDeptList(this.gradeId,this.unitId);
			if(list != null && list.size() > 0){
				opts.append("{");  //保存选项信息
				int counter = 0;                            //计数器
				for(TbUserDept dept:list){
//					如果不是第一项，追加一个“,”用于分隔选项	{'id':'name','id1':'name1'}
	                if (counter > 0) {
	                    opts.append(",");
	                }
	                opts.append("'");
	                opts.append(dept.getId());
	                opts.append("':'");
	                opts.append(dept.getDeptName());
	                opts.append("'");
	                counter++;                      //计数器加1	
				}
				opts.append("}");
			}
			this.contextPvd.getResponse().getWriter().write(opts+"");
			this.contextPvd.getResponse().getWriter().flush();
			this.contextPvd.getResponse().getWriter().close();
		} catch (Exception e) {
			Loggers.error("msgAction:loadDept()出错："+e);
			e.printStackTrace();
		}
	}
	
	public List getDeptList(String gradeId,String unitId){
		try {
			TbUserDept sysDept = this.systemService.getDeptByCode(Util.DEPT_CODE);
			StringBuilder hql = new StringBuilder("from TbUserDept t where 1=1 and t.isDele=0");
			if("2".equals(gradeId)){//安办
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId);
				}else{
					hql.append(" and t.deptType=0 and t.deptGrade=2 and t.deptClass=1");
				}
			}else if("3".equals(gradeId)){//市级科室
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId);
				}else{
					hql.append(" and t.deptType=1 and t.deptGrade=2 and t.deptClass=1");
				}
			}else if("4".equals(gradeId)){//区级科室
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId+" and t.deptType=1");
				}else{
					hql.append(" and t.deptType=3 and t.deptParentId="+sysDept.getId());
				}
			}else if("5".equals(gradeId)){//市行业
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId);
				}else{
					hql.append(" and t.deptType=2 and t.deptGrade=2");
				}
			}else if("6".equals(gradeId)){//区行业
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId+" and t.deptType=2");
				}else{
					hql.append(" and t.deptType=3 and t.deptParentId="+sysDept.getId());
				}
			}else if("7".equals(gradeId)){//属地
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId+" and t.deptType=3");
				}else{
					hql.append(" and t.deptType=3 and t.deptParentId="+sysDept.getId());
				}
			}else if("8".equals(gradeId)){//区安委会
				if(null!=unitId){
					hql.append(" and t.deptParentId="+unitId+" and t.deptType=0");
				}else{
					hql.append(" and t.deptType=3 and t.deptParentId="+sysDept.getId());
				}
			}
			List<TbUserDept> list = (List)this.utilService.getHqlQuery(hql.toString());
			if(null!=list && list.size()>0 && "4".equals(gradeId) && (null==unitId || "".equals(unitId))){
				for(int i=0;i<list.size();i++){
					TbUserDept dept = list.get(i);
					dept.setDeptName(dept.getDeptName()+"安监局");
				}
			}
			if(null!=list && list.size()>0 && "8".equals(gradeId) && (null==unitId || "".equals(unitId))){
				for(int i=0;i<list.size();i++){
					TbUserDept dept = list.get(i);
					dept.setDeptName(dept.getDeptName()+"安委会");
				}
			}
			return list;
		} catch (Exception e) {
			Loggers.error("msgAction:getDeptList()出错："+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 加载添加页面
	 */
	public String loadAdd(){
		try {
			this.checkSearch();//检查是否解码
			result = "msg_add";
			return SUCCESS;
		} catch (Exception e) {
			Loggers.error("MsgAction:loadAdd()出错:"+e);
			e.printStackTrace();
		}
		return ERROR;
	}
	
	/**
	 * 加载数据
	 * 
	 * @return
	 */
	public String loadMsg() {
		try {
			checkSearch();// 检查是否解码
			if (!"".equals(id) && id != null) {
				msg = (TbOaMsg) this.utilService.getObjectById(TbOaMsg.class,Long.parseLong(id));
				newsContent = msg.getMsgContext();
				if (menuId.equals("1")) {
					msg.setReadStatus("1");
					this.utilService.update(msg);
				}				
				msgFjList = (List<TbOaMsgFj>) this.utilService.getHqlQuery("from TbOaMsgFj f where f.msgId = " + msg.getId()+" and f.isDele=0");
				return SUCCESS;
			}
			//加载后的页面由上一页面指定
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("MsgAction:loadMsg()出错！" + e);
		}
		tip = "加载出错！";
		return ERROR;
	}
	
	/**
	 * 保存添加
	 * @return
	 */
	public String addMsg(){
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			msg.setMsgTime(new Date());
			//TODO change
			msg.setTbUser(user);
			msg.setMsgGrade(user.getTbUserGrade().getId());
			if (user.getTbUserDept() != null){
				msg.setMsgDept(user.getTbUserDept().getId());
			}
			if (user.getTbUserUnit()!=null){
				msg.setMsgUnit(user.getTbUserUnit().getId());
			}
			msg.setMsgContext(newsContent);
			msg.setAcceptStatus("0");
			msg.setEditStatus("0");
			msg.setReadStatus("0");
			msg.setIsDele("0");
			this.utilService.save(msg);
			// 有附件上传
			if (!"".equals(docFileName) && docFileName != null) {
				String path = Util.SAFETY_FILE + File.separator + Util.FILE_FOLDER + File.separator + Util.OA_MSG;
				for (int i = 0; i < doc.length; i++) {
					String fileName = upLoadFile(doc[i], path, docFileName[i]);// 上传附件
					msgFj = new TbOaMsgFj();
					String path1 = Util.FILE_FOLDER + File.separator + Util.OA_MSG + File.separator + fileName;
					msgFj.setFjPath(path1);
					msgFj.setFjSize(UtilMethod.getFjSize(doc[i].length() + ""));
					msgFj.setFjTitle(docFileName[i]);
					msgFj.setFjName(fileName);
					msgFj.setFjType(this.suffix);
					msgFj.setIsDele("0");
					msgFj.setTbOaMsg(msg);
					this.utilService.save(msgFj);
				}
			}
			tip = "添加成功！";
			return msgList();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("MsgAction :addMsg()出错" + e);
		}
		tip = "添加失败！";
		return ERROR;
	}
	
	/**
	 * 上传文件
	 */
	public String upLoadFile(File file, String dst, String fileName) {
		suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		String name = "";
		if (checkSuffix(suffix)) {// 判断后缀
			name = UploadFile.copy2(file, dst, fileName);
			return name;
		} else {
			tip = "文件格式非法！";
			return "";
		}
	}
	
	/**
	 * 检查后缀名是否合法
	 */
	public boolean checkSuffix(String suffix) {
		//合法后缀名
		String suf = "jpg,png,bmp,html,htm,doc,xls,ppt";
		if (!"".equals(suf)) {
			String[] sufs = suf.split(",");
			for (String s : sufs) {
				if (suffix.toLowerCase().equals(s)) {
					return true;
				}
			}
			return false;
		}
		return true;
	}
	
	/**
	 * 下载
	 */
	public String downLoad() {
		TbOaMsgFj f = null;
		try {
			if (null != this.fjId && !"".equals(this.fjId)) {
				f = (TbOaMsgFj) this.utilService.getObjectById(TbOaMsgFj.class, Long.parseLong(this.fjId));
					if (!"".equals(f.getFjPath()) && f.getFjPath() != null) {
						if (new File(Util.SAFETY_FILE+File.separator + f.getFjPath()).exists()) {
							this.setFilePath(f.getFjPath().substring(0, f.getFjPath().lastIndexOf("\\") + 1));
							this.setFile(f.getFjPath().substring(f.getFjPath().lastIndexOf("\\") + 1, f.getFjPath().length()));
							this.setFName(new String(f.getFjTitle().getBytes("gbk"), "iso-8859-1"));
							return SUCCESS;
						} else {
							tip = "对不起，文件已删除或不存在";
						}
					}
				}
			tip="查询文件错误!";
		} catch (Exception e) {
			Loggers.error("MsgAction:downLoad出错：" + e);
			e.printStackTrace();
		}
		return ERROR;
	}

	/**
	 * 对于上边的文件路径，给出他的输入流(实际文件资源)，对应在配置文件中的InputName属性名
	 */
	public InputStream getInputStream() {
		InputStream o = null;
		try {
			o = new FileInputStream(Util.SAFETY_FILE+File.separator+filePath+file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return o;
	}
	
	/**
	 * 设置采纳类型信息
	 * @return
	 */
	public String updateAcceptType(){
		try {
			checkSearch();
			TbOaMsg msg = (TbOaMsg) this.utilService.getObjectById(TbOaMsg.class, Long.parseLong(id));
			if (msg != null) {
				StringBuffer tempString = new StringBuffer();
				StringBuffer tempString2 = new StringBuffer();
				if (acceptStatus != null) {
					for (String s : acceptStatus) {
						Object t = this.utilService.getHqlQuery("select t.typeName from TbOaMsgType t where t.id="+s);
						if (t != null){
							String s2 = ((List)t).get(0).toString();
							tempString2.append(s2).append(",");
						}
						tempString.append(s).append(",");
					}
					String temp = tempString.toString().substring(0, tempString.length() - 1);
					String temp2 = tempString2.toString().substring(0, tempString2.length() - 1);
					msg.setAcceptName(temp2);
					msg.setAcceptStatus(temp);
				} else {
					msg.setAcceptStatus("0");
				}
				this.utilService.update(msg);
			}
			addOk = true;
			return loadAcceptType();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("MsgAction:updateAcceptType()出错" + e);
		}
		tip = "编辑失败";
		return ERROR;
	}
	
	/**
	 * 异步附件删除
	 */
	public void deleFj() {
		this.contextPvd.getResponse().setContentType("charset=UTF-8");
		TbOaMsgFj fj = null;
		try {
			if (null != fjId && !"".equals(fjId)) {
				fj = (TbOaMsgFj) this.utilService.getObjectById(TbOaMsgFj.class, Long.parseLong(fjId));
				if (null != fj) {
//					this.utilService.delete(fj);
					fj.setIsDele("1");
					this.utilService.update(fj);
				}
				this.contextPvd.getResponse().getWriter().write("1");
			} else {
				this.contextPvd.getResponse().getWriter().write("2");
			}
			this.contextPvd.getResponse().getWriter().flush();
			this.contextPvd.getResponse().getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.info("msgAction deleFj()方法：" + e);
		}
	}
	
	/**
	 * 保存信息更改
	 * @return
	 */
	public String saveMsg(){
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			this.checkSearch();//检查是否解码
			if (msg != null){
				TbOaMsg tempMsg = (TbOaMsg)this.utilService.getObjectById(TbOaMsg.class, msg.getId());
				if (tempMsg != null){
					tempMsg.setMsgTitle(msg.getMsgTitle());
					tempMsg.setMsgContext(newsContent);
					tempMsg.setMsgTime(new Date());
					//TODO change
					tempMsg.setTbUser(user);
					this.utilService.update(tempMsg);
					tip="修改成功！";
					msgList();
					return SUCCESS;
				} else {
					tip="修改失败！";
				}
			}
			tip = "法律法规调取失败！";
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("msgAction:saveMsg()出错!"+e);
		}
		return ERROR;
	}
	
	/**
	 * 信息上报 上报后不可修改
	 * @return
	 */
	public String issue(){
		try {
			checkSearch();
			search = "1";
			// 修改TbCorpMsg表
			TbOaMsg msg = (TbOaMsg) this.utilService.getObjectById(TbOaMsg.class, Long.parseLong(id));
			if (msg != null) {
				msg.setEditStatus("1");
				this.utilService.update(msg);
			}
			tip = "修改成功";
			msgList();
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("msgAction:issue()出错" + e);
		}
		tip = "编辑失败";
		return ERROR;
	}

	public String getMenuId() {
		return menuId;
	}

	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}

	public String[] getAcceptStatus() {
		return acceptStatus;
	}

	public void setAcceptStatus(String[] acceptStatus) {
		this.acceptStatus = acceptStatus;
	}

	public String getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(String beginDate) {
		this.beginDate = beginDate;
	}

	public File[] getDoc() {
		return doc;
	}

	public void setDoc(File[] doc) {
		this.doc = doc;
	}

	public String[] getDocFileName() {
		return docFileName;
	}

	public void setDocFileName(String[] docFileName) {
		this.docFileName = docFileName;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getFjId() {
		return fjId;
	}

	public void setFjId(String fjId) {
		this.fjId = fjId;
	}

	public String getForwardPage() {
		return forwardPage;
	}

	public void setForwardPage(String forwardPage) {
		this.forwardPage = forwardPage;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public TbOaMsg getMsg() {
		return msg;
	}

	public void setMsg(TbOaMsg msg) {
		this.msg = msg;
	}

	public TbOaMsgFj getMsgFj() {
		return msgFj;
	}

	public void setMsgFj(TbOaMsgFj msgFj) {
		this.msgFj = msgFj;
	}

	public List getMsgFjList() {
		return msgFjList;
	}

	public void setMsgFjList(List msgFjList) {
		this.msgFjList = msgFjList;
	}

	public List getMsgList() {
		return msgList;
	}

	public void setMsgList(List msgList) {
		this.msgList = msgList;
	}

	public String getNewsContent() {
		return newsContent;
	}

	public void setNewsContent(String newsContent) {
		this.newsContent = newsContent;
	}

	public String getReadStatus() {
		return readStatus;
	}

	public void setReadStatus(String readStatus) {
		this.readStatus = readStatus;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public String getFName() {
		return fName;
	}

	public void setFName(String name) {
		fName = name;
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public List getAcceptType() {
		return acceptType;
	}

	public void setAcceptType(List acceptType) {
		this.acceptType = acceptType;
	}

	public String getAcceptTypeForwardId() {
		return acceptTypeForwardId;
	}

	public void setAcceptTypeForwardId(String acceptTypeForwardId) {
		this.acceptTypeForwardId = acceptTypeForwardId;
	}

	public String getDoneAcceptType() {
		return doneAcceptType;
	}

	public void setDoneAcceptType(String doneAcceptType) {
		this.doneAcceptType = doneAcceptType;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getGradeId() {
		return gradeId;
	}

	public void setGradeId(String gradeId) {
		this.gradeId = gradeId;
	}

	public String getUnitId() {
		return unitId;
	}

	public void setUnitId(String unitId) {
		this.unitId = unitId;
	}

	public List getGradeList() {
		return gradeList;
	}

	public void setGradeList(List gradeList) {
		this.gradeList = gradeList;
	}

	public String getCDept() {
		return cDept;
	}

	public void setCDept(String dept) {
		cDept = dept;
	}

	public String getCGrade() {
		return cGrade;
	}

	public void setCGrade(String grade) {
		cGrade = grade;
	}

	public String getCUnit() {
		return cUnit;
	}

	public void setCUnit(String unit) {
		cUnit = unit;
	}

	public boolean isAddOk() {
		return addOk;
	}

	public void setAddOk(boolean addOk) {
		this.addOk = addOk;
	}
}
